﻿/**
 * Author:chzhcpu@gmail.com
 *  
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace PatentButcher
{
    public partial class MainForm : Form
    {
        private List<string> lstpns = new List<string>();
        private string rsltFolder = AppDomain.CurrentDomain.BaseDirectory+"PatentFiles\\";
        public MainForm()
        {
            InitializeComponent();
            if (!Directory.Exists(rsltFolder))
                Directory.CreateDirectory(rsltFolder);

            lbPatNum.Items.Add("US6800782");lstpns.Add("US6800782");
            lbPatNum.Items.Add("CN1727329");lstpns.Add("CN1727329");
            lbPatNum.Items.Add("EP1743655");lstpns.Add("EP1743655");

            lvDownState.Columns.Add("Pat PubNo");
            lvDownState.Columns.Add("Status");
            lvDownState.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            lvDownState.Columns[0].Width = lvDownState.Width*1/3-20;
            lvDownState.Columns[1].Width = lvDownState.Width * 2 / 3;
        }

        private void WorkCompleteHandler(object sender, TaskEventArgs args)
        {
            string msg = args.Progress;
            if (msg.IndexOf("对象引用")>-1)
            {
                msg = "没有找到可以下载的文件";
            }
            ListViewItem item = new ListViewItem();
            foreach (ListViewItem it in lvDownState.Items)
            {
                if (it.Text != args.PN)
                    continue;
                else
                {
                    item = it;
                    break;
                }
            }
            // new ListViewItem(args.PN);
            item.SubItems[1].Text=msg;
            if (args.Progress.IndexOf("100") > -1)
            {
                item.ForeColor = Color.Green;
            }
            else
                item.ForeColor = Color.Red;
            //lvDownState.Items.Add(item);
        }

        private void btnAddPN_Click(object sender, EventArgs e)
        {
            string pn=tbPatNum.Text;
            if (string.IsNullOrEmpty(pn))
                return;
            if (lstpns.IndexOf(pn) > -1)
                MessageBox.Show("存在重复输入的专利号！");
            else
            {
                lbPatNum.Items.Add(pn);
                lstpns.Add(pn);
            }
            tbPatNum.Text = "";
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

        private void tbPatNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                btnAddPN_Click(sender, e);
                tbPatNum.Text = "";
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.CheckFileExists = true;
            ofd.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string fn = ofd.FileName;
                StreamReader sr = new StreamReader(fn);
                string line = "";
                while (!string.IsNullOrEmpty(line = sr.ReadLine()))
                {
                    if (lstpns.IndexOf(line) < 0)
                    {
                        lbPatNum.Items.Add(line);
                        lstpns.Add(line);
                    }
                    else
                    {
                        MessageBox.Show("存在重复的专利号："+line);
                    }
                }
            }
        }

        private void lbPatNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Delete)
            {
                while (lbPatNum.SelectedIndex > -1)
                {
                    string item = lbPatNum.SelectedItem.ToString();
                    lstpns.Remove(item);
                    lbPatNum.Items.Remove(item);
                }
                //lbPatNum.DataSource = lstpns;
            }
        }

        private void btnOpenDLFolder_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", this.rsltFolder);
        }

        private void btnAbout_Click(object sender, EventArgs e)
        {
            AboutForm abf = new AboutForm();
            abf.ShowDialog();
        }

        private void btnEspDownload_Click(object sender, EventArgs e)
        {
            lvDownState.Items.Clear();
            for (int i = 0; i < lbPatNum.Items.Count; i++)
            {
                string pn = lbPatNum.Items[i].ToString().ToUpper();

                espPatentGrabber espg = new espPatentGrabber(pn);
                espg.WorkComplete += new TaskEventHandler(WorkCompleteHandler);
                ThreadPool.QueueUserWorkItem(new WaitCallback(espg.SearchbyPN));
                ListViewItem item = new ListViewItem(pn);
                item.SubItems.Add("开始下载...");
                lvDownState.Items.Add(item);

            }

        }

        private void btnCnDownload_Click(object sender, EventArgs e)
        {
            lvDownState.Items.Clear();
            for (int i = 0; i < lbPatNum.Items.Count; i++)
            {
                string pn = lbPatNum.Items[i].ToString().ToUpper();

                if (pn.Substring(0, 2) == "CN")
                {
                    cnPatentGrabber cng = new cnPatentGrabber(pn);
                    cng.WorkComplete += new TaskEventHandler(WorkCompleteHandler);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(cng.SearchbyPN));
                    ListViewItem item = new ListViewItem(pn);
                    item.SubItems.Add("开始下载...");
                    lvDownState.Items.Add(item);
                }
                /*else
                {
                    espPatentGrabber espg = new espPatentGrabber(pn);
                    espg.WorkComplete += new TaskEventHandler(WorkCompleteHandler);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(espg.SearchbyPN));
                    ListViewItem item = new ListViewItem(pn);
                    item.SubItems.Add("开始下载...");
                    lvDownState.Items.Add(item);
                }*/
            }
        }

        private void btnUSDownload_Click(object sender, EventArgs e)
        {
            lvDownState.Items.Clear();
            for (int i = 0; i < lbPatNum.Items.Count; i++)
            {
                string pn = lbPatNum.Items[i].ToString().ToUpper();
                if (pn.Substring(0, 2) == "US"&&pn.Substring(2).Length==7)
                {
                    usPatentGrabber usg = new usPatentGrabber(pn);
                    usg.WorkComplete += new TaskEventHandler(WorkCompleteHandler);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(usg.SearchbyPN));
                    ListViewItem item = new ListViewItem(pn);
                    item.SubItems.Add("开始下载...");
                    lvDownState.Items.Add(item);
                }
                /*else
                {
                    espPatentGrabber espg = new espPatentGrabber(pn);
                    espg.WorkComplete += new TaskEventHandler(WorkCompleteHandler);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(espg.SearchbyPN));
                    ListViewItem item = new ListViewItem(pn);
                    item.SubItems.Add("开始下载...");
                    lvDownState.Items.Add(item);
                }*/
            }
        }

        private void btnClearAll_Click(object sender, EventArgs e)
        {
            lbPatNum.Items.Clear();
            lvDownState.Items.Clear();
            lstpns.Clear();
        }

        private void buttonDelTempFile_Click(object sender, EventArgs e)
        {
            string[] dirs= Directory.GetDirectories(this.rsltFolder);
            foreach (string dir in dirs)
            {
                FileAttributes fileattr = File.GetAttributes(dir);
                if (fileattr.ToString().ToLower().IndexOf("hidden")>-1)
                    continue;

                string[] files= Directory.GetFiles(dir);
                if (files.Length <1)
                    Directory.Delete(dir);
                else
                {
                    string filename =dir+"\\"+ dir.Substring(dir.LastIndexOf("\\")+1)+".pdf";
                    if (!File.Exists(filename))
                    {
                        continue;
                    }
                    else
                    {
                        //delete temp image file or pdf file only having one page
                        foreach (string file in files)
                        {
                            if (file.ToLower().Equals(filename.ToLower()))
                                continue;
                            try
                            {
                                File.Delete(file);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                    }
                }
            }
        }

    }
}
